package com.cloud.pay.controller;

import com.cloud.pay.constant.PayChannelEnum;
import com.egzosn.pay.common.bean.PayOutMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Writer;

/**
 * 支付通知接口
 */
@Slf4j
@RestController
public class PayNotifyController {
    /**
     * 微信支付通知
     *
     * @param appId
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping(value="/payNotify/wxpay/{appId}")
    public void wxPayNotify(@PathVariable("appId") String appId, HttpServletRequest request, HttpServletResponse response) throws IOException {
        PayOutMessage payOutMessage = PayChannelEnum.WECHAT_PAY.getPayAdapter().payBack(appId, request.getParameterMap(), request.getInputStream());
        if (payOutMessage != null) {
            writeResult(response, payOutMessage.toMessage());
        }
    }

    /**
     * 支付宝支付通知
     *
     * @param appId
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping(value="/payNotify/alipay/{appId}")
    public void aliPayNotify(@PathVariable("appId") String appId, HttpServletRequest request, HttpServletResponse response) throws IOException {
        PayOutMessage payOutMessage = PayChannelEnum.ALI_PAY.getPayAdapter().payBack(appId, request.getParameterMap(), request.getInputStream());
        if (payOutMessage != null) {
            writeResult(response, payOutMessage.toMessage());
        }
    }

    private void writeResult(HttpServletResponse response, String result) throws IOException {
        Writer writer = response.getWriter();
        writer.write(result);
        writer.flush();
    }
}
